package myJs.components

import cats.effect.SyncIO
import japgolly.scalajs.react._
import japgolly.scalajs.react.component.Scala.BackendScope
import japgolly.scalajs.react.extra.StateSnapshot
import japgolly.scalajs.react.vdom.all._
import myJs.Implicits._
import myJs.myPkg.jquery._
import myJs.tool.Tool

/**
 * Created by yz on 3/11/2020
 */
object InputGroupComponent {

  case class Props(state: StateSnapshot[String], show: Boolean = false, label: String, name: String) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  class Backend(bs: BackendScope[Props, Unit]) {

    val fieldNames = List(bs.props.unsafeRunSync().name)

    def didMount = {
      SyncIO {
        Tool.popover
        ()
      }
    }

    def didUpdate(p: Props) = {
      SyncIO {
        val bv = $("#form").bv
        val node = ReactDOM.findDOMNode(bs.raw).get.node
        val parentJq = $(node)
        fieldNames.foreach { fieldName =>
          val curJq = parentJq.findInputByName(fieldName)
          if (p.show) {
            bv.revalidateField(curJq)
          } else {
            bv.updateStatus(curJq, "VALID")
          }
        }
      }
    }

    def render(p: Props) = {

      val s = p.state.value
      div(`class` := "form-group col-sm-12", (display := "none").unless(p.show),
        label(
          s"${p.label}", ":"
        ),
        div(`class`:="input-group",
          PureInputComponent.Props(p.state,name = p.name).render,
          span(`class` := "input-group-addon", "%")
        )
      )

    }

  }

  val Component = ScalaComponent.builder[Props].renderBackend[Backend].
    componentDidMount(x => x.backend.didMount).
    componentDidUpdate(x => x.backend.didUpdate(x.currentProps)).
    build

}



